package cn.yunhe.servlet;

import cn.yunhe.entity.News;
import cn.yunhe.service.NewsService;
import cn.yunhe.util.DateUtil;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

//by郭瀚钰
@WebServlet("/AddNewsServlet")
public class AddNewsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=================进入模块");
        SmartUpload sm = new SmartUpload();
        JspFactory jspFactory = JspFactory.getDefaultFactory();
        PageContext pageContext = jspFactory.getPageContext(this,request,response,null,true,8192,true);
        sm.initialize(pageContext);
        sm.setCharset("UTF-8");
        try {
            sm.setAllowedFilesList("jpg,bmp");
            sm.upload();
            sm.save("fileup");
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        Request req = sm.getRequest();
        String title = req.getParameter("title");
        String context =  req.getParameter("content");
        int enflag =  Integer.parseInt(req.getParameter("enflag"));
        int parentClass =0;
        if(req.getParameter("parentClass")!=null) {
            parentClass = Integer.parseInt(req.getParameter("parentClass"));
        }
        int ChildClass = 0;
        if(req.getParameter("ChildClass")!=null) {
            ChildClass = Integer.parseInt(req.getParameter("ChildClass"));
        }
        int epcid = 0;
        if( req.getParameter("epid")!=null) {
            epcid = Integer.parseInt(req.getParameter("epid"));
        }
        String pic = sm.getFiles().getFile(0).getFileName();
        News news = new News(title,context,DateUtil.getCurrTime(),enflag,pic,epcid,parentClass,ChildClass);
        NewsService newsService = new NewsService();
        Boolean flag = newsService.addNews(news);
        PrintWriter out = response.getWriter();
        response.setContentType("text/html;charset=UTF-8");
        if (flag){//发布成功
            out.print("<script>alert('发布成功')<script>");
            response.sendRedirect("manage/news.jsp");
        }else{
            out.print("<script>alert('发布失败,请检查填写内容')<script>");
            response.sendRedirect("manage/news-add.jsp");
        }



    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
